﻿using System;
using RedisLock;
using System.Threading;
using System.Threading.Tasks;

namespace MyConsole
{
    class Program
    {
        private static string lockKey = "lockkey";

        static void Main(string[] args)
        {
            LockHelper.Init("127.0.0.1:6379");


            bool quit = false;

            while (!quit)
            {
                //这里测试同步方法
                //TestLockSync();

                //这里测试异步方法
                TestLockAsync();

                Console.WriteLine("按回车继续运行，输入exit回车退出程序。");
                quit = Console.ReadLine() == "exit";
            }
        }

        private static void TestLockAsync()
        {
            Task.Run(() =>
            {
                GetLockAsync();
            });

            Task.Run(() =>
            {
                GetLockAsync();
            });
        }

        private static async void GetLockAsync()
        {
            string threadName = Thread.CurrentThread.ManagedThreadId.ToString();
            Console.WriteLine($"[线程{threadName}] [{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}] 开始获取锁");

            if(await LockHelper.LockAsync(lockKey))
            {
                Console.WriteLine($"[线程{threadName}] [{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}] 已经获取到锁");
                await Task.Delay(5000);
                LockHelper.Release(lockKey);
                Console.WriteLine($"[线程{threadName}] [{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}] 已经释放锁");
            }
            else
            {
                Console.WriteLine($"[线程{threadName}] [{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}] 没有获取到锁");
            }
        }

        /// <summary>
        /// 测试同步方法锁
        /// </summary>
        private static void TestLockSync()
        {
            Thread t1 = new Thread(new ThreadStart(GetLockSync));
            t1.Name = "1";

            Thread t2 = new Thread(new ThreadStart(GetLockSync));
            t2.Name = "2";

            t1.Start();
            t2.Start();
        }

        static void GetLockSync()
        {
            string threadName = Thread.CurrentThread.Name;

            Console.WriteLine($"[线程{threadName}] [{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}] 开始获取锁");

            if (LockHelper.Lock(lockKey))
            {
                Console.WriteLine($"[线程{threadName}] [{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}] 已经获取到锁");

                Thread.Sleep(5000);
                LockHelper.Release(lockKey);
                Console.WriteLine($"[线程{threadName}] [{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}] 已经释放锁");
            }
            else
            {
                Console.WriteLine($"[线程{threadName}] [{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}] 没有获取到锁");
            }
        }
    }

    
}
